var express = require('express')
var app = express()

//如果session.属性名 不存在则返回undefined
var session = require('express-session')
app.use(session({
    // 配置加密字符串，它会在原有加密基础之上和这个字符串拼起来去加密
    // 目的是为了增加安全性，防止客户端恶意伪造
    secret: 'duckling',
    resave: false,
    saveUninitialized: false // 无论你是否使用 Session ，我都默认直接给你分配一把钥匙
}))

//express处理post请求的中间件
var bodyParser = require('body-parser')
// 配置模板引擎和 body-parser 一定要在 app.use(router) 挂载路由之前
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

//mongoose数据库模块
var mongoose = require('mongoose')
//连接MongoDB数据库
mongoose.connect('mongodb://127.0.0.1:27017/duckling',{ useNewUrlParser: true });
mongoose.connection.on("connected", function () {
    console.log("MongoDB connected success.")
});
mongoose.connection.on("error", function () {
    console.log("MongoDB connected fail.")
});
mongoose.connection.on("disconnected", function () {
    console.log("MongoDB connected disconnected.")
});

//var history = require('connect-history-api-fallback');
//app.use(history());

//导入路由模块
var registerRouter = require('./routers/registerRouter')
var loginRouter = require('./routers/loginRouter')
var authRouter = require('./routers/authRouter')

app.all('/api/*',(req,res,next) => {
    //req.get('字段名') 获取请求头某字段的信息
    //通过此设置可以防范外部访问api接口
    //生产环境下开启,为了测试方便,开发环境下不开启
    //var referer = req.get('Referer')
    //if(referer !== 'http://localhost:8080/'){
    //    return res.send('<h1>无权访问!</h1>')
    //}
    next()
})

//app.all('/api/*', (req, res, next) => {
//    //设置允许跨域响应报文头
//    //设置跨域
//    // 启用 Node 服务器端的 cors 跨域
//    res.header("Access-Control-Allow-Origin", "*");
//    res.header("Access-Control-Allow-Headers", "X-Requested-With");
//    res.header("Access-Control-Allow-Methods", "*");
//    res.setHeader('Content-Type', 'application/json;charset=utf-8');
//    next();
//});

app.use('/api/register',registerRouter)
app.use('/api/login',loginRouter)
app.use('/api/auth',authRouter)


app.listen('3000',() => {
    console.log('server started at port 3000')
})
